package com.hwtx.form.domain.ds;

import com.hwtx.form.domain.FormConstants;

import java.util.Objects;

import static com.hwtx.form.domain.FormConstants.DEFAULT_DS_NAME;
import static com.hwtx.form.domain.FormConstants.JDBC_PREFIX;

public class DataSourceContextHolder {

    private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();

    public static void checkDataSourceKey(String key) {
        if (!Objects.equals(DEFAULT_DS_NAME, key)) {
            setDataSourceKey(JDBC_PREFIX + key);
        } else {
            setDefaultDsKey();
        }
    }

    public static void setDefaultDsKey() {
        contextHolder.set(FormConstants.DEFAULT_DS_NAME);
    }

    public static String getDataSourceKey() {
        return contextHolder.get();
    }

    public static void setDataSourceKey(String key) {
        if (key == null) {
            setDefaultDsKey();
        } else {
            if (!key.startsWith(JDBC_PREFIX)) {
                key = JDBC_PREFIX + key;
            }
            contextHolder.set(key);
        }
    }

    public static void clearDataSourceKey() {
        contextHolder.remove();
    }

    public static String getDefaultDs() {
        return DEFAULT_DS_NAME;
    }
}